import { createSlice } from '@reduxjs/toolkit'
// import { request } from '@/utils/request'
import { login } from '@/apis/login'
import { getUserInfo as getUserInfoApi } from '@/apis/user'
import { setToken as setTokenToStorage, getToken, removeToken as removeTokenFromStorage } from '@/utils/token'

const userStore = createSlice({
    name: 'user',
    initialState: {
        token: getToken() || '',
        userInfo: {},
        // token: '',
    },
    reducers: {
        setToken: (state, action) => {
            state.token = action.payload
            // setTokenToStorage(action.payload)
        },
        setUserInfo: (state, action) => {
            state.userInfo = action.payload
        },
        removeToken: (state) => {
            state.token = ''
            removeTokenFromStorage()
        }
    }
})

const { setToken, setUserInfo, removeToken } = userStore.actions
//异步登录 获取token
const loginAction = (params) => {
    return async (dispatch) => {
        // const res = await request.post('/authorizations', params)
        const res = await login(params)
        console.log(res)
        if (res.data.data.token) {
            dispatch(setToken(res.data.data.token))
            setTokenToStorage(res.data.data.token)
        }
    }
}

const getUserInfo = (params) => {
    return async (dispatch) => {
        // const res = await request.post('/authorizations', params)
        const res = await getUserInfoApi(params)
        dispatch(setUserInfo(res.data.data))
        console.log(res.data.data)
    }
}


export { setToken, loginAction, getUserInfo, removeToken }

const reducer = userStore.reducer

export default reducer